<template>
    <Dialog v-model="dialogVisible" title="排课设置" width="65%">
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="140px" v-loading="formLoading">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="拼团名称">
                        <span>{{formData.name}}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="教练" prop="person">
                        <el-select v-model="formData.person" placeholder="请选择教练">
                            <el-option v-for="item, index in userList" :key="index" :label="item.username" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="上课时间" prop="list">
                        <el-table :data="formData.list" border>
                            <el-table-column label="课时" align="center">
                                <template #default="{ $index }">
                                    <span>课时{{$index + 1}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="上课日期" align="center">
                                <template #default="{ row }">
                                    <el-date-picker class="w-100%!" v-model="row.date" value-format="x" type="date" placeholder="请选择上课时间" />
                                </template>
                            </el-table-column>
                            <el-table-column label="开始时间" align="center">
                                <template #default="{ row, $index }">
                                    <el-time-select
                                        v-model="row.startTime"
                                        start="00:00"
                                        step="00:10"
                                        end="23:59"
                                        placeholder="选择时间"
                                        @change="handleChangeStartTime($index)" />
                                </template>
                            </el-table-column>
                            <el-table-column label="结束时间" align="center">
                                <template #default="{ row }">
                                    <el-time-select
                                        v-model="row.endTime"
                                        :start="row.startTime || '00:00'"
                                        step="00:10"
                                        end="23:59"
                                        placeholder="选择时间" />
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" align="center" width="120">
                                <template #default="scope">
                                    <el-button link type="primary" @click="handleAdd()">
                                        新增
                                    </el-button>
                                    <el-button :disabled="scope.$index == 0" link type="primary" @click="handleDelete(scope.$index)">
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="dialogVisible = false">取 消</el-button>
        </template>
    </Dialog>
</template>
<script lang="ts" setup>
import * as CombinationActivityApi from '@/api/mall/promotion/combination/combinationActivity'
import * as UserApi from '@/api/system/user'
import { CombinationProductVO } from '@/api/mall/promotion/combination/combinationActivity'
import { cloneDeep } from 'lodash-es'

defineOptions({ name: 'PromotionCombinationActivityForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formRef = ref() // 表单 Ref
const list = ref([getCourseDate()])
const rules = reactive({
    person: [required],
    list: {
        required: true,
        validator: (rule, value, callback) => {
            let valid = true;
            value.forEach(item => {
                if (!item.date || !item.startTime || !item.endTime) {
                    valid = false;
                }
            })
            if (!valid) {
                return callback('【上课时间】设置不完善，请填写相关信息');
            }
            callback();
        }
    }
})
const userList = ref([]); // 用户（教练）列表

/** 初始化表单 */
function getForm() {
    return {
        name: '1',
        person: '',
        list: [getCourseDate()]
    }
}
/** 初始化排课 */
function getCourseDate() {
    return {
        date: '',
        startTime: '',
        endTime: ''
    }
}
const formData = ref(getForm())

/** 监听开始时间变化，清空对应的结束时间 */
const handleChangeStartTime = (index: number) => {
    formData.value.list[index].endTime = '';
}
/** 新增子项 */
const handleAdd = () => {
    formData.value.list.push(getCourseDate());
}

/** 删除子项 */
const handleDelete = (index: number) => {
    formData.value.list.splice(index, 1)
}

// ================= end =================

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
    dialogVisible.value = true
    await resetForm()
    // 修改时，设置数据
    if (id) {
        // formLoading.value = true
        try {
            const data = (await CombinationActivityApi.getCombinationActivity(
                id
            )) as CombinationActivityApi.CombinationActivityVO
            
            formData.value = data;
            // formRef.value.setValues(data)
        } finally {
            // formLoading.value = false
        }
    }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = async () => {
    formData.value = getForm();
    await nextTick()
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
    // 校验表单
    await formRef.value.validate()
    // 提交请求
    formLoading.value = true
    try {
        // 真正提交
        const data = cloneDeep(formData.value);
        // if (formType.value === 'create') {
        //     await CombinationActivityApi.createCombinationActivity(data)
        //     message.success(t('common.createSuccess'))
        // } else {
        //     await CombinationActivityApi.updateCombinationActivity(data)
        //     message.success(t('common.updateSuccess'))
        // }
        dialogVisible.value = false
        // 发送操作成功的事件
        emit('success')
    } finally {
        formLoading.value = false
    }
}

/** 查询所有用户列表 */
const getAllUser = () => {
    UserApi.getUserPage({
        pageNo: 1,
        pageSize: 100
    }).then(res => {
        userList.value = res.list;
    })
}

onMounted(() => {
    getAllUser();
})
</script>
